<template>
	<view class="channel-container" :style="{ paddingTop: channel.channelContainerPaddingTop + 'px' }" v-if="initializationParams">
		<view class="channel-title" :class="{ fixed: channel.isTop }" :style="{ top: channel.channelTitleHeight + 'px' }">
			<scroll-view class="channel-title-list" :scroll-left="scrollLeft" scroll-x="true">
				<view class="channel-title-item" v-for="(item, index) in title" :key="index" @click="slideChannelSwiper(index, item.title)">
					<view class="title" :class="current == index ? 'active' : ''">{{ item.title }}</view>
					<view class="subtitle">{{ item.subTitle }}</view>
				</view>
			</scroll-view>
		</view>
		<swiper class="swiper-channel" @change="onChannelSwiperChange" :current="current" :style="{ height: channelSwiperHeight + 'px' }">
			<swiper-item class="swiper-channel-page" v-for="(pageItem, pageIndex) in data" :key="pageIndex">
				<view class="channel-flex-container">
					<!-- <product-item v-for="(item, index) in data[pageIndex]" :key="index" :item="item" :index="index" :title="title[pageIndex]" :fragmentId="fragmentId"></product-item> -->
					<view class="history-reload-more" v-if="title[pageIndex].showHistoryMore" @click="handleHistoryReload">点击查看更多商品</view>
					<product-item :spuList="data[pageIndex]" :moduleOrder="moduleOrder" :title="title[current].subTitle" :refModuleId="'1004'"  @openNormsModal="openNormsModal" :isShowAddCart="isShowAddCart"></product-item>
				</view>
				<view class="brose-history" @click="handleNavBrowseHistory" v-if="title[pageIndex].showHasHistory">
					<view class="word">跳到上次浏览的位置</view>
					<view class="img-view" @click.stop="closeShowHistory(pageIndex)">
						<image class="close" src="/static/img/integralMall/close.png"></image>
					</view>
				</view>
			</swiper-item>
		</swiper>
		<spe-modal ref="speModal"></spe-modal>
		<load-more :status="status" @retry="loadMore"></load-more>
	</view>
</template>

<script>
import productItem from '../common/productItem.vue';
import speModal from '@/components/speModal.vue'
import browseHistory from '@/sevice/productBrowseHistory'
import SearchRandom from '@/module/searchRandom'
import Product from '@/module/product'
export default {
	components: {
		productItem,
		speModal
	},
	props: {
		initializationParams: {
			type: String,
			default: ''
		},
		fragmentId: {
			type: Number,
			default: 0
		},
		searchFixed: {
			type: Boolean,
			default: false
		},
		isShowSearch: {
			type: [Boolean, Number],
			default: false
		},
		//主题活动页是否展示标题
		isShowHeader: {
			type: [Number,String],
			default: 1
		},
		definedEntrance: {
			type: String,
			default: ''
		},
		//来源模块在页面的排序序号
		moduleOrder: {
			type: [Number,String],
			default: 0
		}
	},
	inject: ['exposure'],
	data() {
		return {
			entrance: this.$globalData.state.entrance,
			channelSwiperHeight: uni.upx2px(542),
			current: 0,
			title: [
				{
					title: '全部',
					subTitle: '为你推荐'
				}
			],
			data: [],
			// 当前tab状态
			status: 'hide',
			channel: {
				isTop: false, // 频道区标题是否置顶
				channelContainerPaddingTop: uni.upx2px(16), //
				channelTitleHeight: 0 // 频道区标题高度
			},
			// 最小滚动位置
			minScrollTop: null,
			// 记录每个频道的滚动位置
			lastScrollTopArr: [],
			scrollLeft: 0,
			titleWidthArr: [],
			dataArr: [],
			isShowAddCart:false//是否显示购物车按钮
		};
	},
	created() {
		this.title = JSON.parse(this.initializationParams);
		if (this.title) {
			for (let i = 0; i < this.title.length; i++) {
				this.title[i].pageNo = 0;
				this.title[i].status = 'hide';
				this.title[i].SearchRandom = new SearchRandom()
				this.data.push([]);
			}
			this.isShowAddCart = this.title[this.current].showAddShoppingCar ? true:false
			this.joinSource(this.current, this.title[this.current].sourceType, this.title[this.current].sourceValue, this.title[this.current].groupId||0);
		}
		this.exposure.setMarkHistoryPageType('channelProduct')
	},
	computed:{
		cityInfo(){
			return uni.getStorageSync('eoc-good-city')? uni.getStorageSync('eoc-good-city'): this.$globalData.state.cityInfo.default
		},
		headerHeight() {
			return this.$globalData.state.headerHeight
		}
	},
	mounted() {
		const query = uni.createSelectorQuery().in(this);
		query
			.selectAll('.channel-title-item')
			.boundingClientRect(data => {
				this.dataArr = data;
			})
			.exec();
	},
	methods: {
		queryBrowseHistory() {
			const historyKey = `${this.title[this.current].sourceType}-${this.title[this.current].sourceValue}`
			const hasHistory = browseHistory.queryPageHistory('channelProduct', historyKey)
			if (hasHistory) {
				const localTitle = this.title[this.current]
				localTitle.beforeHistory = hasHistory
				localTitle.showHasHistory = true
				const current = this.current
				localTitle.hisToryTime = setTimeout(() => {
					localTitle.showHasHistory = false
					this.$set(this.title, current, localTitle)
				}, 8000)
			}
		},
		closeShowHistory(current) {
			const localTitle = this.title[this.current]
			clearTimeout(localTitle.hisToryTime)
			localTitle.showHasHistory = false
			this.$set(this.title, this.current, localTitle)
		},
		handleNavBrowseHistory() {
			const history = this.title[this.current].beforeHistory
			const source = history.key.split('-')
			if (!history) return
			if (history.pageIndex < 11) {
				_loadAllProduct.call(this, history)
			} else {
				_loadPartProduct.call(this, history)
			}
			this.closeShowHistory()

			function _loadAllProduct(history) {
				this.joinSource(this.current, source[0], source[1],this.title[this.current].groupId||0,1, history.pageIndex * 6).then(() => {
					this.$nextTick(async () => {
						const position = await this.exposure.findProductPosition(history.productId)
						if (!position) return
						this.scrollTo(position.top + 50)
					})
				})
			}

			async function _loadPartProduct(history) {
				this.data[this.current] = []
				let loadPage = history.pageIndex + 2
				this.title[this.current].pageNo = history.pageIndex - 1
				for(let i = 1; i < 4 ; i++) {
					await this.joinSource(this.current, source[0], source[1],this.title[this.current].groupId||0)
				}
				const localTitle = this.title[this.current]
				localTitle.showHistoryMore = true
				localTitle.showHasHistory = false
				this.$set(this.title, this.current, localTitle)
				this.title[this.current].pageNo = loadPage
				this.$nextTick(async () => {
					const position = await this.exposure.findProductPosition(history.productId)
					if (!position) return
					this.scrollTo(position.top + 50)
				})
			}
		},
		handleHistoryReload() {
			const localTitle = this.title[this.current]
			localTitle.showHistoryMore = false
			const history = this.title[this.current].beforeHistory
			browseHistory.deletePageHistory('channelProduct', history.key)
			this.data[this.current] = []
			localTitle.pageNo = 0;
			localTitle.status = 'hide';
			this.$set(this.title, this.current, localTitle)
			this.joinSource(this.current, localTitle.sourceType, localTitle.sourceValue,this.title[this.current].groupId||0)
		},
		scrollTo(index) {
			uni.pageScrollTo({
				scrollTop: index,
				duration: 300
			});
		}, //置顶按钮
		onChannelSwiperChange(e) {
			this.current = e.detail.current;
			let currWidth = this.dataArr[this.current].width;
			console.log(currWidth);
			this.scrollLeft = (this.current - 1) * currWidth;

			/* 使标题栏居中 */
			// let titleList = uni.createSelectorQuery().select('.channel-title-list');
			// if (this.current > 2) {
			// 	// 标题栏滚动，选中的title滚到中间位置
			// 	titleList.scrollLeft = (this.current + 1) * uni.upx2px(142) - uni.upx2px(71) - uni.upx2px(750 / 2)
			// } else {
			// 	titleList.scrollLeft = 0;
			// }
			// 设置swiper高度
			let height = uni.upx2px(1088);
			if (this.data[this.current] && this.data[this.current].length > 4) {
				height = Math.max(height, uni.upx2px(542) * Math.ceil(this.data[this.current].length / 2));
			}
			this.channelSwiperHeight = height;
			console.log('set swiper height', height);
			// 滚动到原来位置
			if (this.minScrollTop && this.channel.isTop) {
				uni.pageScrollTo({ scrollTop: this.lastScrollTopArr[this.current] || this.minScrollTop, duration: 0 });
			}
			if (this.title[this.current].status !== 'end') {
				this.joinSource(this.current, this.title[this.current].sourceType, this.title[this.current].sourceValue,this.title[this.current].groupId||0);
			} else {
				this.status = 'end';
			}
		},
		slideChannelSwiper(index, title) {
			this.current = index;
		},
		/**
		 * 查询数据
		 */
		queryData(currentIndex, url, param, ifByIdList = false) {
			let ifByIdListParam = ifByIdList ? { pageNo: 1 } : {} // 指定商品。页码请求时改为1。param里的页码不变
			return this.$request(url, Object.assign({}, param, ifByIdListParam), 'api', false).then(
				data => {
					if (ifByIdList) data.total = ifByIdList.length // 指定商品。商品总数为数组总数，前端替换下。
					this.status = 'hide';
					this.title[currentIndex].status = this.status;
					let spuList = data.spuList;
					if (spuList && spuList.length > 0) {
						//console.log('query')
						var dealSpuList = [];
						const historyMark = Object.assign({}, param, {
							sourceType: this.title[currentIndex].sourceType,
							sourceValue: this.title[currentIndex].sourceValue
						})
						spuList.forEach((item, index) => {
							let price = item.minSalePrice / 100 + '';
							price = price.split('.');
							item.interger = price[0];
							if (price[1]) {
								item.fractional = price[1];
							}
							if (param.pageNo == 1 && param.pageSize !== 6) {
								historyMark.pageNo = parseInt(index / 6) + 1
							}
							item.historyMark = JSON.stringify(historyMark)
							item.salesCount = this.$utils.formatNum(item.salesCount);
							dealSpuList.push(item)
						});
						// 如果是当前频道初次加载且有商品就查询历史记录
						if (!this.data[currentIndex].length && dealSpuList.length && !this.title[currentIndex].isRandom) {
							if (!this.title[currentIndex].isRandom) {
								this.queryBrowseHistory()
							}
						}
						// 如果列表是前端随机的，商品要随机而要初始化分页的最大值。
						if (this.title[currentIndex].isRandom && url == 'search/searchSpu') {
							dealSpuList = dealSpuList.sort((a, b) => Math.random() > 0.5 ? -1 : 1)
							if (param.pageNo == 1) this.title[currentIndex].SearchRandom.initTotal(param.pageNo, param.pageSize, data.total)
						}
						this.data[currentIndex] = param.pageNo == 1 ? dealSpuList : this.data[currentIndex].concat(dealSpuList);
						this.$forceUpdate();

						const randomLock = this.title[currentIndex].isRandom && url == 'search/searchSpu' && param.pageNo == 101 // 前端随机排序，商品搜索超过101页，关闭搜索

						if ((param.pageNo * param.pageSize >= data.total) || randomLock) {
							this.status = 'end';
							this.title[currentIndex].status = this.status;
						}
						const coutSpuList = this.isShowNoStock ? this.data[currentIndex] : this.data[currentIndex].filter(spu => spu.haveStock)
						// set channelSwiper height
						if (coutSpuList.length > 2) {
							this.channelSwiperHeight = uni.upx2px(542) * Math.ceil(coutSpuList.length / 2);
						}
						const hasStockList = this.data[currentIndex].filter(pro => pro.haveStock)
						if (hasStockList.length < 6) {
							this.loadMore()
						}
					} else {
						this.status = 'end';
						this.title[currentIndex].status = this.status;
					}
				},
				res => {
					this.status = 'fail';
					this.title[currentIndex].status = this.status;
				}
			);
		},
		joinSource(currentIndex, sourceType, sourceValue, groupId, pageNo, pageSize) {
			const currentParam = this.title[currentIndex]
			const status = currentParam.status;
			if (status === 'loading' || status === 'end') {
				return;
			}
			this.status = 'loading';
			currentParam.status = this.status;
			let url = '' // 请求的url地址
			let data = {} // 请求的参数
			let ifByIdList = false // 是否ID列表，前端进行ID分页
			if (sourceType == '200') {
				url = 'operation/queryProductListByGroup';
				data.groupId = sourceValue;
			} else if (sourceType == '201') {
				url = 'search/searchSpu'; // 1.23版本替换搜索接口
				// url = 'operation/queryProductListByGroup';
				// data.groupId = groupId;
				data.categoryIdList = sourceValue; // 1.23版本替换搜索接口
				// data.fetchAdditionalInfo = 0; 1.23版本替换搜索接口
			} else if (sourceType == '202') {
				url = 'search/searchSpu';
				data.keyWord = sourceValue;
				data.fetchAdditionalInfo = 0;
			} else if (sourceType == '203') {
				//商品id数组
				url = 'product/spu/list';
				ifByIdList = sourceValue
				// 如果是指定商品。前端要对数组进行分页，pageNo为1，数组前端切割
				data.idList = Product.searchProductByIdPaging(sourceValue, currentParam.pageNo + 1, pageSize || 20)
			} else if (sourceType == '205') {
				url = 'search/searchSpu';
				data.intellectualPropertyIdList = [sourceValue];
				data.fetchAdditionalInfo = 0;
			} else if (sourceType == '207') {
				//品牌
				url = 'search/searchSpu';
				data.brandIdList = [sourceValue];
				data.fetchAdditionalInfo = 0;
			} else if (sourceType == '208') {
				// 指定课程
				url = 'product/spu/list';
				// 如果是指定商品。前端要对数组进行分页，pageNo为1，数组前端切割
				data.idList = Product.searchProductByIdPaging(sourceValue, currentParam.pageNo + 1, pageSize || 20)
				ifByIdList = sourceValue
			} else if (sourceType == '209') {
				// 指定课程
				url = 'product/spu/pageCourseSpu';
				data.courseCategoryIdList = sourceValue;
			} else if (sourceType == '210') {
				// 指定课程
				url = 'product/spu/pageCourseSpu';
				data.courseLabelList = sourceValue;
			} else if (sourceType == '211') {
				// 指定供应商
				url = 'search/searchSpu';
				data.supplierCode = [sourceValue];
				if (currentParam.brandType == 2) data.brandIdList = currentParam.brandIdList
				if (currentParam.categoryType == 2) data.categoryIdList = currentParam.categoryIdList
			}
			console.log('isShowNewGoods', this.title[this.current].isShowNewGoods);
			data.isRandom = this.title[this.current].isRandom || 0
			if (this.title[this.current].isShowNewGoods == 1) {
				// 新品专区
				data.showDay = this.title[this.current].showDay,
				data.isShowNewGoods = this.title[this.current].isShowNewGoods
				url = 'search/simpleSearchSpu'
			}

			data.isRandom = this.title[this.current].isRandom
			data.pageSize = pageSize || 20;
			if (pageNo == 1 && pageSize !== 20) {
				data.pageNo = pageNo
				this.title[currentIndex].pageNo = pageSize / 20
			} else {
				data.pageNo = ++this.title[currentIndex].pageNo
			}

			if (url == 'search/searchSpu' && data.isRandom) {
				data = this.title[currentIndex].SearchRandom.formParam(data)
			}

			return this.queryData(currentIndex, url, data, ifByIdList);
		},
		goToGoodDetail(spuId) {
			this.$routeUtils.navigateTo({
				url: '/pages/goods/detail?spuId=' + spuId
			});
		},
		loadMore() {
			this.joinSource(this.current, this.title[this.current].sourceType, this.title[this.current].sourceValue, this.title[this.current].groupId||0);
		},
		pageScroll(obj) {
			let headerBarHeight = this.headerHeight;
			if (this.definedEntrance == 'index' && this.$globalData.state.frontConfig.isShowPoint && this.isShowSearch) {
				if (this.entrance == 'h5' || this.entrance == 'weixin') headerBarHeight = 0
				headerBarHeight += uni.upx2px(88);
			} else if (this.definedEntrance == 'other') {
				if (!this.isShowHeader) headerBarHeight = 0
				if (this.searchFixed) headerBarHeight = this.headerHeight;
			}
			console.log('什么东西', headerBarHeight)
			uni.createSelectorQuery().in(this)
				.select('.channel-container')
				.boundingClientRect(rect => {
					if (rect.top < headerBarHeight) {
						if (!this.channel.isTop) {
							console.log('2', obj.scrollTop);
							this.minScrollTop = obj.scrollTop;
							this.channel.isTop = true;
							console.log('pageScroll', headerBarHeight);
							this.channel.channelTitleHeight = headerBarHeight;
							this.channel.channelContainerPaddingTop = uni.upx2px(88 + 24);
						} else {
							this.lastScrollTopArr[this.current] = obj.scrollTop;
						}
					} else {
						this.channel.isTop = false;
						this.channel.channelTitleHeight = 0;
						this.channel.channelContainerPaddingTop = uni.upx2px(16);
					}
					if(this.isShowHeader != 1){//主题活动页标题不展示时，频道top设置为0
						this.channel.channelTitleHeight = 0;
					}
				})
				.exec();
		},
		openNormsModal(spuId){//打开购物弹窗
			this.$Login.checkLoginingblock(() => {
				if(this.$refs.speModal){
				  this.$refs.speModal.initData(spuId);
				}
			})
		}
	}
};
</script>

<style lang="scss" scoped>
.channel-container {
	.channel-title {
		text-align: left;
		.channel-title-list {
			list-style: none;
			margin: 0;
			padding: 0;
			white-space: nowrap;
			text-align: left;
			.channel-title-item {
				margin: 0;
				padding: 0 24rpx;
				box-sizing: content-box;
				display: inline-block;
				.title {
					color: #333;
					font-size: 30rpx;
					display: block;
					text-align: center;
					height: 44rpx;
					width: 100%;
					line-height: 44rpx;
					padding-left: 16rpx;
					padding-right: 16rpx;
					white-space: nowrap;
					box-sizing: border-box;
				}

				.title.active {
					color: #ff004f;
					// background-color: #FF004F;
					// border-radius: 44rpx;
				}

				.subtitle {
					color: #999;
					font-size: 22rpx;
					display: block;
					text-align: center;
					line-height: 32rpx;
					margin-top: 4rpx;
					margin-bottom: 15rpx;
					white-space: nowrap;
				}
			}
		}
	}

	.channel-title.fixed {
		position: fixed;
		left: 0;
		background-color: #fff;
		z-index: 10;
		height: 88rpx;
		width: 100%;

		.channel-title-list .channel-title-item .title {
			margin-top: 23rpx;
		}

		.channel-title-list .channel-title-item .subtitle {
			display: none;
		}
	}

	.swiper-channel {
		padding: 0 15rpx;
		width: 100%;
		box-sizing: border-box;

		.swiper-channel-page {
			position: relative;
			.channel-flex-container {
				margin: 0 -15rpx;

				.channel-flex-item {
					width: 342rpx;
					height: 526rpx;
					border-radius: 8rpx;
					background-color: #ffffff;
					margin: 9rpx;
					position: relative;
					box-sizing: border-box;
					overflow: hidden;

					.image {
						width: 342rpx;
						height: 342rpx;
						background-color: #eaeaea;
						display: block;
					}

					.des {
						font-size: 26rpx;
						color: #333;
						margin: 20rpx 24rpx 0 24rpx;
						line-height: 36rpx;
						display: block;
						text-align: left;
						overflow: hidden;
						text-overflow: ellipsis;
						display: -webkit-box;
						-webkit-line-clamp: 2;
						-webkit-box-orient: vertical;
					}

					.items {
						position: absolute;
						bottom: 30rpx;
						text-align: left;

						.price {
							margin-left: 24rpx;
							margin-right: 16rpx;
							color: #ff004f;
							font-size: 32rpx;
							font-weight: 600;

							.small {
								font-size: 28rpx;
							}
						}

						.payments {
							margin-right: 24rpx;
							font-size: 24rpx;
							color: #999;
						}
					}
				}
			}
		}
	}

	.channel-load-msg {
		width: 100%;
		height: 116rpx;
		padding: 40rpx 0;

		.channel-loading {
			width: 50rpx;
			height: 20rpx;
			margin: 8rpx auto;
			position: relative;

			//display: none;
			.dot {
				width: 20rpx;
				height: 20rpx;
				border-radius: 100%;
				position: absolute;
			}

			.red {
				background-color: #ff004f;
				animation: dotLoading 1.8s alternate infinite linear;
			}

			.blue {
				background-color: #a000b0;
				animation: dotLoading -0.9s 1.8s alternate infinite linear;
			}
		}

		.channel-loaded {
			color: #999;
			font-size: 26rpx;
			//display: none;
		}
	}
}

.brose-history{
	position: absolute;
	top: 37rpx;
	right: 20rpx;
	width: 324rpx;
	height: 76rpx;
	background: #333333;
	border-radius: 16rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	.word{
		color: #fff;
		font-size: 28rpx;
	}
	.img-view{
		height: 100%;
		display: flex;
		align-items: center;
		.close{
			margin-left: 10rpx;
			width: 33rpx;
			height: 33rpx;
		}
	}
}

.history-reload-more{
	height: 80rpx;
	background-color: #f6f6f6;
	text-align: center;
	line-height: 70rpx;
	color: #999;
	font-size: 24rpx;
}

@keyframes dotLoading {
	0% {
		left: 0;
	}

	50% {
		left: 30rpx;
	}

	100% {
		left: 0;
	}
}
</style>
